<template>
  <el-form
    ref="formRef"
    :model="model"
    :rules="rules"
    label-width="100px"
    class="gen-form"
  >
    <!-- 普通组件 -->
    <template v-for="item in formData" :key="item.id">
      <template v-if="item.type !== 'grid' && item.type !== 'card'">
        <el-form-item
          :label="item.name"
          :prop="item.id"
          :rules="item.options?.rulesConfig?.rules"
        >
          <element-comps
            :element="item"
            v-model="model[item.id]"
            @change="handleValueChange"
          />
        </el-form-item>
      </template>
      
      <!-- 栅格布局 -->
      <template v-else-if="item.type === 'grid'">
        <el-row
          :gutter="item.options.gutter"
          :justify="item.options.justify"
          :align="item.options.align"
          class="grid-layout"
        >
          <el-col
            v-for="(col, colIndex) in item.options.columns"
            :key="colIndex"
            :span="col.span"
            class="grid-col"
          >
            <template v-for="(colItem, itemIndex) in col.list" :key="itemIndex">
              <el-form-item
                :label="colItem.name"
                :prop="colItem.id"
                :rules="colItem.options?.rulesConfig?.rules"
              >
                <element-comps
                  :element="colItem"
                  v-model="model[colItem.id]"
                  @change="handleValueChange"
                />
              </el-form-item>
            </template>
          </el-col>
        </el-row>
      </template>
      
      <!-- 容器布局 -->
      <template v-else-if="item.type === 'container'">
        <div 
          class="container-layout"
          :style="{ 
            padding: item.options.padding,
            background: item.options.background
          }"
        >
          <div v-if="item.options.showHeader" class="container-header">
            {{ item.options.title }}
          </div>
          <div class="container-body">
            <template v-for="(containerItem, itemIndex) in item.options.list" :key="itemIndex">
              <el-form-item
                :label="containerItem.name"
                :prop="containerItem.id"
                :rules="containerItem.options?.rulesConfig?.rules"
              >
                <element-comps
                  :element="containerItem"
                  v-model="model[containerItem.id]"
                  @change="handleValueChange"
                />
              </el-form-item>
            </template>
          </div>
        </div>
      </template>
    </template>
  </el-form>
</template>

<script setup>
import { ref, onMounted, toRefs, watch } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import ElementComps from "./ElementComps.vue";
import { makeRange, computedDateRangeM } from "../../../../utils";

const store = useStore();

const props = defineProps({
  formData: {
    type: Array,
    default: () => []
  },
  gridData: {
    type: Array,
    default: () => []
  }
});

const { formData } = toRefs(props);
const formRef = ref(null);
const model = ref({});
const rules = ref({});

// 初始化表单数据和校验规则
const initForm = () => {
  // 清空旧数据
  model.value = {};
  rules.value = {};

  // 处理所有组件
  formData.value?.forEach(item => {
    if (item.type === 'grid') {
      // 处理栅格布局中的组件
      item.options.columns.forEach(col => {
        col.list?.forEach(colItem => {
          if (colItem && colItem.id) {
            model.value[colItem.id] = colItem.options?.defaultValue;
            if (colItem.options?.rulesConfig?.rules) {
              rules.value[colItem.id] = colItem.options.rulesConfig.rules;
            }
          }
        });
      });
    } else if (item.type === 'card') {
      // 处理卡片布局中的组件
      item.options.list?.forEach(cardItem => {
        if (cardItem && cardItem.id) {
          model.value[cardItem.id] = cardItem.options?.defaultValue;
          if (cardItem.options?.rulesConfig?.rules) {
            rules.value[cardItem.id] = cardItem.options.rulesConfig.rules;
          }
        }
      });
    } else if (item.id) {
      // 处理普通组件
      model.value[item.id] = item.options?.defaultValue;
      if (item.options?.rulesConfig?.rules) {
        rules.value[item.id] = item.options.rulesConfig.rules;
      }
    }
  });
};

// 处理值变更
const handleValueChange = (value, id) => {
  model.value[id] = value;
  console.log('form data changed:', model.value); // 用于调试
};

// 获取表单数据
const getData = () => {
  return new Promise((resolve, reject) => {
    formRef.value?.validate((valid) => {
      if (valid) {
        console.log("submit!", JSON.stringify(model.value));
        resolve(model.value);
      } else {
        console.log("error submit!");
        reject(false);
      }
    });
  });
};

defineExpose({ getData });

/* 监听表单数据变化 */
watch(() => props.formData, () => {
  initForm();
}, { immediate: true });

/**
 * 日期区间相关
 */
// 计算开始时间到结束时间的时长
const computedDateRange = (element) => {
  computedDateRangeM(element, formData);
};

// 日期区间时间选择器禁用掉的时间（用于禁掉起始时间的判断）
const disabledHours = () => {
  // 父时间相等时才能进行子时间的判断
  if (
    !!formData.value.beginParentDateValue &&
    formData.value.beginParentDateValue === formData.value.endParentDateValue
  ) {
    const H = formData.value.beginChildDateValue.split(":")[0];
    return makeRange(0, H - 1);
  }
};

const disabledMinutes = (hour) => {
  const H = formData.value.beginChildDateValue.split(":")[0];
  const m = formData.value.beginChildDateValue.split(":")[1];

  // 父时间相等时才能进行子时间的判断
  if (
    !!formData.value.beginParentDateValue &&
    formData.value.beginParentDateValue === formData.value.endParentDateValue
  ) {
    if (hour === +H) {
      return makeRange(0, +m);
    }
  }
};
</script>

<style lang="scss" scoped>
.title {
  display: inline-block;
  margin-bottom: 8px;
  .require-icon {
    position: relative;
    &::after {
      content: "*";
      position: absolute;
      left: 100%;
      top: -2px;
      line-height: 20px;
      padding-left: 2px;
      color: #f54a45;
    }
  }
}

/* 布局组件样式 */
.layout-container {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 16px;

  .layout-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 16px;
    font-weight: 500;
  }

  .layout-content {
    display: grid;
    gap: 16px;

    &.col-2 {
      grid-template-columns: repeat(2, 1fr);
    }

    &.col-3 {
      grid-template-columns: repeat(3, 1fr);
    }

    &.col-4 {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  .layout-column {
    :deep(.el-form-item) {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .el-form-item__label {
        font-size: 13px;
        color: #606266;
      }

      .el-form-item__content {
        line-height: 32px;
      }

      .el-input__wrapper {
        height: 32px;
      }

      .el-input__inner {
        height: 32px;
        line-height: 32px;
        font-size: 13px;
      }
    }
  }
}

/* 响应式处理 */
@media screen and (max-width: 768px) {
  .layout-content {
    &.col-3,
    &.col-4 {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

@media screen and (max-width: 480px) {
  .layout-content {
    &.col-2,
    &.col-3,
    &.col-4 {
      grid-template-columns: 1fr;
    }
  }
}

.gen-form {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  
  // 栅格布局样式
  .grid-layout {
    margin: 16px 0;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;
    
    .grid-col {
      padding: 0 12px;
      
      :deep(.el-form-item) {
        margin-bottom: 18px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  // 容器布局样式
  .container-layout {
    margin: 16px 0;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    
    .container-header {
      padding: 12px 16px;
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      border-bottom: 1px solid #e4e7ed;
    }
    
    .container-body {
      padding: 16px;
      
      :deep(.el-form-item) {
        margin-bottom: 18px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  // 表单项样式
  :deep(.el-form-item) {
    margin-bottom: 18px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .el-form-item__label {
      font-size: 14px;
      color: #606266;
    }
  }
}
</style>
